//插入核心模块
const http = require("http");
const fs = require("fs");

//创建服务器
const app = http.createServer((request, respone) => {
    getInquire();
    getDelete();
    getModify();
    getPost();

})

//开启监听。3000是端口，3000到10000之间最好，太少就有电脑其他软件端口占用
app.listen(3000, () => {
    console.log("服务启动成功端口好为3000，访问地址为 http://127.0.0.1:3000");
});


//查询全部和单个的函数
function getInquire() {
    //查询
    //提前对url和请求参数做处理。
    const [url, query] = request.url.split("?");
    const usp = new URLSearchParams(query);
    //读取文件
    let list = fs.readFileSync("./data.json", "utf8");
    //转化为数组
    list = JSON.parse(list);
    if (request.method === "GET" && url === "/list") {
        respone.end(JSON.stringify({ code: 0, message: "查询成功过", data: list }))
    } else if (request.method === "GET" && url === "/one") {
        const id = usp.get("id");
        //one会返回一个数组
        const one = list.find((v) => v.id == id)
        if (one) {
            respone.end(JSON.stringify({ code: 0, message: "查询成功", data: one }))
        } else {
            respone.end({ code: "1", message: "找不到改内容" })
        }
    } else {
        //没有查到总的
        respone.statusCode = 404;
        respone.end("not ok")

    }

}

//delete部分
function getDelete() {
    const [url, query] = request.url.split("?");
    const usp = new URLSearchParams(query);
    let list = fs.readFileSync("./data.json", "utf8");
    list = JSON.parse(list);
    if (request.method === "DELETE" && url === "/delete") {
        const id = usp.get("id");
        const one = list.find((v) => v.id == id);
        if (one) {
            list.splice(one.id - 1, 1);
            fs.writeFileSync("./data.json", JSON.stringify(list));
            respone.end(JSON.stringify({ code: 0, message: "删除成功" }))
        } else {
            respone.end(JSON.stringify({ code: 1, message: "找不到该数据" }))
        }
    } else {
        respone.statusCode = 404;
        respone.end("not ok");
    }
}

//修改部分
function getModify() {
    //  定义变量 接收数据
    if (request.method === "PUT") {
        let dataStr = "";
        request.on("data", (chunk) => {
            // chunk 块 - 客户端请求的参数
            dataStr += chunk;
        });
        //接受完变量才能运行下面的操作
        request.on("end", function () {
            //读取文件
            let list = fs.readFileSync("./data.json", "utf8");
            //转化为数据方便寻找到对应值
            list = JSON.parse(list)
            const usp = new URLSearchParams(dataStr);
            const obj = {};
            //拿到新传递过来的值
            const id = usp.get("id");
            // usp 也是可以遍历 也有自己的forEach方法
            usp.forEach((val, key) => {
                obj[key] = val;
            });
            //找到要修改的对象的对应值
            const one = list.find((v) => v.id == id);
            //判断是否有要修改的值
            if (one) {
                //判断只要有一个为空都不行
                if (obj.name == "" || obj.gender == "") {
                    //有一个为空时输出判断修改失败
                    respone.end(JSON.stringify({ code: 1, message: "修改失败，不能传递空值" }))
                } else {
                    //有对应修改值时就做出对应的替换
                    const num = one.id - 1;
                    obj.id = +obj.id;
                    list.splice(num, 1, obj);
                    // 重新写回本地文件
                    fs.writeFileSync("./data.json", JSON.stringify(list));
                    respone.end(JSON.stringify({ code: 0, message: "修改成功", data: obj }));
                }

            } else {
                respone.end(JSON.stringify({ code: 1, message: "修改失败，找不到该数据" }))
            }
        })
    }
}

//post 增加部分
function getPost() {
    //post 增加部分
    //定义变量 接收数据
    if (request.method === "POST") {
        let dataStr = "";
        request.on("data", (chunk) => {
            dataStr += chunk;
        })
        request.on("end", function () {
            const usp = new URLSearchParams(dataStr);
            const obj = {};
            usp.forEach((val, key) => {
                obj[key] = val;
            });
            obj.creator = null;
            let list = fs.readFileSync("./data.json");
            list = JSON.parse(list);
            list.push(obj);
            fs.writeFileSync("./data.json", JSON.stringify(list))
            respone.end(JSON.stringify({ code: 0, message: "添加成功", data: obj }))
        })
    }
}